#include "UtorrentApi.h"

#include <QtCore/QDebug>
#include <QDomDocument>

UtorrentApi::UtorrentApi(QObject *parent,QString serveur,QString port,QString user,QString password)
	: QObject(parent), serveur(serveur), port(port), auth(user+":"+password)
{
	waitingToken = false;

	nam = new QNetworkAccessManager(this);
	connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));

	getToken();
}

UtorrentApi::~UtorrentApi()
{
	if(nam!=NULL)
	{
		disconnect(nam, SIGNAL(finished(QNetworkReply*)),  this, SLOT(finishedSlot(QNetworkReply*)));
		delete nam;
	}
	nam=NULL;


}

void UtorrentApi::finishedSlot(QNetworkReply* reply)
{
	// Reading attributes of the reply
	// e.g. the HTTP status code
	QVariant statusCodeV = 
		reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	// Or the target URL if it was a redirect:
	QVariant redirectionTargetUrl =
		reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
	// see CS001432 on how to handle this

	QString demande = reply->request().attribute (QNetworkRequest::User).toString() ;
	// no error received?
	if (reply->error() == QNetworkReply::NoError)
	{
		QByteArray bytes = reply->readAll();  // bytes

		if(demande == "TOKEN")
		{
			QDomDocument doc;
			doc.setContent(bytes,false,0,0);
			QDomNodeList docElemList = doc.elementsByTagName("div");
			QDomNode node = docElemList.at(0);
			token = node.toElement().text();
			//qDebug()<<token;
			waitingToken = false;

			if(!token.isEmpty())
			{
				for(QString item : waiting)
				{
					if(item=="LIST")
						getList();
					if(item=="GETSETTINGS")
						getSettings();
				}
				waiting.clear();
			}
		}
		else
		{
			QJsonDocument json = QJsonDocument::fromJson(bytes);
			emit resultReceive(demande,json);
		}

	}
	// Some http error received
	else
	{
		if(demande == "TOKEN")
			waitingToken = false;
		else token = "";
		emit errorReceive(demande,statusCodeV.toInt(),reply->error(),reply->errorString());

	}

	// We receive ownership of the reply object
	// and therefore need to handle deletion.
	delete reply;
}


QString UtorrentApi::getToken()
{
	if(token.isEmpty())
	{
		waitingToken = true;
		QUrl url("http://"+auth+"@"+serveur+":"+port+"/gui/token.html");
		QNetworkRequest request(url);
		request.setAttribute(QNetworkRequest::User,QString("TOKEN"));         


		QNetworkReply* reply = nam->get(request);
	}
	return token;
}

void UtorrentApi::getList()
{
	if(!token.isEmpty())
	{
		QUrl url("http://"+auth+"@"+serveur+":"+port+"/gui/?token="+token+"&list=1");
		QNetworkRequest request(url);
		request.setAttribute(QNetworkRequest::User,QString("LIST"));

		QNetworkReply* reply = nam->get(request);
	}
	else
	{
		if(!waiting.contains("LIST"))
			waiting<<"LIST";
		if(!waitingToken)
			getToken();
	}
}
void UtorrentApi::getSettings()
{
	if(!token.isEmpty())
	{
		QUrl url("http://"+auth+"@"+serveur+":"+port+"/gui/?token="+token+"&action=getsettings");
		QNetworkRequest request(url);
		request.setAttribute(QNetworkRequest::User,QString("GETSETTINGS"));

		QNetworkReply* reply = nam->get(request);
	}
	else
	{
		if(!waiting.contains("GETSETTINGS"))
			waiting<<"GETSETTINGS";
		if(!waitingToken)
			getToken();
	}
}

void UtorrentApi::setSetting(QString parametre, QString valeur)
{
	if(!token.isEmpty())
	{
		QUrl url("http://"+auth+"@"+serveur+":"+port+"/gui/?token="+token+"&action=setsetting&s="+parametre+"&v="+valeur);
		QNetworkRequest request(url);
		request.setAttribute(QNetworkRequest::User,QString("SETSETTING"));

		QNetworkReply* reply = nam->get(request);
	}
	else
	{
		/*waiting<<"SETSETTING";*/
		if(!waitingToken)
			getToken();
	}
}